var util = require('../../utils/util.js');
var ajax = require('../../utils/ajax.js');
var common = require('../../utils/common.js');
var Base = require('../base.js');
var app = getApp();

Page(common.extendPage(Base, {

  data: {
    imgUrl: '',
    dataLoaded: false
  },

  onShareAppMessage: function() {
    return {
      title: this.data.shop.shareTitle,
      path: "pages/shopIndex/shopIndex"
    }
  },

  onLoad: function(options) {
    var _self = this;

    _self._initApp(function() {
      _self._initPage();
      _self._quietLogin();

      util.jumpByScene(options.scene);
    });
  },

  _initApp(cb) {
    wx.getExtConfig && wx.getExtConfig({
      success: function(res) {
        var {
          host,
          alias
        } = res.extConfig;

        if (host) {
          app.setHost(host);
        }
        if (alias) {
          app.setAlias(alias);
        }
        cb && cb();
      }
    });
  },

  _initPage: function() {
    var _self = this;

    ajax.P('/openapi/CHome/index', {}, function(result) {
      var data = result.result;
      var shop = {
        name: data.title,
        phone: data.contact,
        address: data.address,
        time: data.hours,
        logo: data.logo,
        shareTitle: data.share_title,
        kfState: data.kf_state,
        shop_img: data.shop_img
      };
      _self.setData({
        shop,
        imgUrl: data.shop_img,
        dataLoaded: true,
      });
      app.setShop(shop);
    });
  },

  /**
   * 跳转至腾讯地图
   */
  _gotoMap() {
    var shop = this.data.shop;

    ajax.G('/openapi/CAddress/getLocation', {
      addr: shop.address
    }, function(data) {
      var addrInfo = JSON.parse(data.result)['result'];

      wx.openLocation({
        latitude: addrInfo.location.lat,
        longitude: addrInfo.location.lng,
        name: shop.name,
        address: shop.address,
      })
    })
  },

  /**
   * 拨打门店电话
   */
  _callPhone: function() {
    var shop = this.data.shop;

    wx.makePhoneCall({
      phoneNumber: shop.phone
    })
  },

  /**
   * openid静默登陆
   */
  _quietLogin: function() {
    var $this = this;

    wx.login({
      success: function(res) {
        ajax.G(
          '/openapi/CHome/getUserOpenID', {
            jscode: res.code
          },
          function(d) {
            app.setOpenId(d.result.openid);
            $this._openIdLogin(d.result.openid);
          }
        );
      },
      fail: function() {},
      complete: function() {}
    })
  },

  /**
   * openid静默登陆
   */
  _openIdLogin: function(openid) {
    var $this = this;
    ajax.P(
      '/openapi/CHome/login', {
        openId: openid
      },
      function(d) {
        var userSid = d.result.userSid;
        if (userSid) {
          app.setUserSid(userSid);
        }
      }
    );
  },
  
  _preview: function() {
    wx.previewImage({
      current: this.data.imgUrl, // 当前显示图片的http链接
      urls: [this.data.imgUrl] // 需要预览的图片http链接列表
    })
  }

}))